package com.czhlearn.interceptors;

import com.czhlearn.pojo.Result;
import com.czhlearn.utils.JwtUtil;
import com.czhlearn.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @program: big-event
 * @description:
 * @author: czh
 * @create: 2023-12-18 14:50
 **/

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        令牌验证
        String token = request.getHeader("Authorization");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String name = method.getName();
        System.out.println(name+"=="+method);
        //验证token
        try {

            //从Redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redistoken = operations.get(token);

            if (redistoken==null){
                //token 已经失效
                throw new RuntimeException();
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);
//            把业务数据存储到Threadlocal
            ThreadLocalUtil.set(claims);
//            放行
            return true;
        } catch (Exception e) {
            //http状态码为401
            response.setStatus(401);
//            不放心
            return false;

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清空Threadlocal 中的数据
        ThreadLocalUtil.remove();
    }
}
